<?php


	namespace app\services;


	use app\lib\exception\ToastException;
	use app\model\User;

	class UserServices
	{

		public function lst () {


			/*$list = User::field('uid,nickname,phone')->limit(0,10)->order('uid','desc')->select();*/

			$arr = [
				0 => ['id' => 21, 'pid' => 0, 'name' => '安徽省21', 'distance' => 21.21],
				1 => ['id' => 22, 'pid' => 0, 'name' => '浙江省22', 'distance' => 22.22],
				2 => ['id' => 33, 'pid' => 1, 'name' => '合肥市33', 'distance' => 33.33],
				3 => ['id' => 44, 'pid' => 2, 'name' => '长丰县44', 'distance' => 44.44],
				4 => ['id' => 55, 'pid' => 1, 'name' => '安庆市55', 'distance' => 55.44],
				5 => ['id' => 66, 'pid' => 3, 'name' => '肥西市66', 'distance' => 55.43],
				6 => ['id' => 17, 'pid' => 3, 'name' => '肥东县17', 'distance' => 17.17],
				7 => ['id' => 11, 'pid' => 2, 'name' => '肥东县11', 'distance' => 11.11],
				8 => ['id' => 18, 'pid' => 2, 'name' => '肥东县11', 'distance' => 0],
				9 => ['id' => 19, 'pid' => 2, 'name' => '肥东县11', 'distance' => 0],
			];



			return $arr;

		}


		function price ($url) {
			$price = '';

			$san = '/^\d{3}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/';//111.com
			$si = '/^[a-z]{4}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/';//sdfd.com
			$qi = '/^[a-z]{7}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/';//adfghjl.com
			$pingyi = '((bang|ba[ino]?|beng|be[in]?|bing|bia[no]?|bi[en]?|bu|cang|ca[ino]?|ceng|ce[in]?|chang|cha[ino]?|cheng|che[n]?|chi|chong|chou|chuang|chua[in]|chu[ino]?|ci|cong|cou|cuan|cu[ino]?|dang|da[ino]?|deng|de[in]?|dia[no]?|ding|di[ae]?|dong|dou|duan|du[ino]?|fang|fan|fa|feng|fe[in]|fo[u]?|fu|gang|ga[ino]?|geng|ge[in]?|gong|gou|guang|gua[in]?|gu[ino]?|hang|ha[ino]?|heng|he[in]?|hong|hou|huang|hua[in]?|hu[ino]?|jiang|jia[no]?|jiong|ji[nu]?|juan|ju[en]?|kang|ka[ino]?|keng|ke[n]?|kong|kou|kuang|kua[in]?|ku[ino]?|lang|la[ino]?|leng|le[i]?|liang|lia[no]?|ling|li[enu]?|long|lou|luan|lu[no]?|lv[e]?|mang|ma[ino]?|meng|me[in]?|mia[no]?|ming|mi[nu]?|mo[u]?|mu|nang|na[ino]?|neng|ne[in]?|niang|nia[no]?|ning|ni[enu]?|nong|nou|nuan|nu[on]?|nv[e]?|pang|pa[ino]?|pa|peng|pe[in]?|ping|pia[no]?|pi[en]?|po[u]?|pu|qiang|qia[no]?|qiong|qing|qi[aenu]?|quan|qu[en]?|rang|ra[no]|reng|re[n]?|rong|rou|ri|ruan|ru[ino]?|sang|sa[ino]?|seng|se[n]?|shang|sha[ino]?|sheng|she[in]?|shi|shou|shuang|shua[in]?|shu[ino]?|si|song|sou|suan|su[ino]?|tang|ta[ino]?|teng|te|ting|ti[e]?|tia[no]?|tong|tou|tuan|tu[ino]?|wang|wa[ni]?|weng|we[in]|w[ou]|xiang|xia[no]?|xiong|xing|xi[enu]?|xuan|xu[en]|yang|ya[no]?|ye|ying|yi[n]?|yong|you|yo|yuan|yu[en]?|zang|za[ino]?|zeng|ze[in]?|zhang|zha[ino]?|zheng|zhe[in]?|zhi|zhong|zhou|zhuang|zhua[in]?|zhu[ino]?|zi|zong|zou|zuan|zu[ino]?))';
			$danpingyin = '/^' . $pingyi . '(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/';//zhang.com
			$shuangpingyin = '/^' . $pingyi . '{2}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/';//lisi.com
			$zami = '/^([a-z]*\d*){0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/';//a1a1.com
			$zami = '/^([a-z]\d){0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/';//a1a1.com

			if (preg_match($san, $url)) {
				$price = '三位数字品相价格';
			} else if (preg_match($si, $url)) {
				$price = '四位纯声母品相价格';
			} else if (preg_match($qi, $url)) {
				$price = ' 7位字母品相价格';
			} else if (preg_match($danpingyin, $url)) {
				$price = ' 单拼音品相价格';
			} else if (preg_match($shuangpingyin, $url)) {
				$price = ' 双拼音品相价格';
			} else if (preg_match($zami, $url)) {
				$price = ' 杂米品相价格';
			}

			return $price;
		}


		public function list ($request) {
			$uid = $request->get('uid');

			$item = User::where('uid', '=', $uid)->field('uid,nickname,spread_uid')->find();

			if (!$item) {
				throw new ToastException('该用户不存在或已删除');
			}

			$list = User::alias('u')->fieldRaw("u.nickname,u.uid,count(eu.uid) as total")->join('eb_user eu', 'eu.spread_uid=u.uid', 'left')->where([
				['u.is_promoter', '=', 1],
				['u.m_level', '>', 3]
			])->group('u.uid')->having('total>0')->order('total', 'desc')->limit(50)->select();

			$keyword = '谢';

			$list = User::field('nickname,uid,spread_uid')->where('spread_uid', '=', function ($query) use ($keyword) {
				$query->table('eb_user')->field('uid')->where("nickname", 'LIKE', "%" . $keyword . "%")->limit(1);
			})->select();


			$qrCodeServices = app(QrCodeServices::class);
			$qr_image = $request->domain() . '/' . $qrCodeServices->createWxaCode('pages/index/index?username=zhangsan&user_id=12');

			$subscribeMessageServices = app(SubscribeMessageServices::class);
			$list = $subscribeMessageServices->getTemplateList();


			return compact('list', 'qr_image');
		}

		//验证token是否过期
		public function verify ($request) {
			//			$token = $request->get("token");
			//
			//			$is_verify = false;
			//			if ($token == 123456) {
			//				return compact('is_verify');
			//			}
			return $request->param();
		}


		public function pay ($request) {
			$snapPayServices = app(SnapPayServices::class);

			return $snapPayServices->pay();
		}

		public function login () {
			$url = 'https://www.chengmi.cn';
			$post = 'usename=&password=123456';

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);//post方式提交
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

			curl_exec($ch);
			curl_close($ch);
		}


		protected function send ($data) {
			$url = 'http://domain.aliyuncs.com/?';

			$params = $this->Signature($data);
			$ret = $this->XmlToArr(file_get_contents($url . http_build_query($params)));

			return $ret;
		}

		/**
		 * 检测域名可否注册
		 *
		 * @param $DomainName
		 *
		 * @param
		 *
		 * @return string
		 * @throws
		 *
		 */
		function checkDomainName ($DomainName) {
			$url = 'http://domain.aliyuncs.com/?';
			$params = Signature(['DomainName' => $DomainName, 'Action' => 'CheckDomain']);

			$ret = $this->XmlToArr(file_get_contents($url . http_build_query($params)));

			if (array_key_exists('Avail', $ret) && $ret['Avail'] == 1) {
				return true;
			} else {
				return false;
			}

		}


		/**
		 * 查询订单
		 *
		 * @param $OrderID
		 *
		 * @param
		 *
		 * @return mixed
		 * @throws
		 *
		 */
		function QueryOrder ($OrderID) {
			$url = 'http://domain.aliyuncs.com/?';
			$params = Signature(['OrderID' => $OrderID, 'Action' => 'QueryOrder']);
			$ret = $this->XmlToArr(file_get_contents($url . http_build_query($params)));

			if (array_key_exists('OrderInformationInvalid', $ret)) {
				return $ret['OrderInformationInvalid'];
			} else {
				return $ret['OrderProducts'];
			}
		}

		/**
		 * @param $OrderID
		 *
		 * @param
		 *
		 * @return mixed|string
		 * @throws
		 *
		 */
		function CreateOrder ($OrderID) {
			$orderProducts = $this->QueryOrder($OrderID);
			$url = 'http://domain.aliyuncs.com/?';
			$params = Signature('CreateOrder', ['SubOrderParam' => $orderProducts]);
			$ret = $this->XmlToArr(file_get_contents($url . http_build_query($params)));

			if (array_key_exists('OrderID', $ret)) {
				return '购买成功';
			} else {
				return $ret;
			}
		}

		//生成签名
		protected function Signature ($data) {
			//
			$access_key_id = 'access_key_id_123456';
			$access_key_secret = 'access_key_secret_123456';

			$params = [
				'SignatureNonce'   => random(16, true),
				'SignatureVersion' => '1.0',
				'Timestamp'        => date("Y-m-d\TH:i:s.0000\Z"),
				'SignatureMethod'  => 'HMAC-SHA1',
				'AccessKeyId'      => $access_key_id,
				'Version'          => '2016-05-11',
			];

			$params = array_merge($params, $data);

			$params['Signature'] = $this->computeSignature($params, $access_key_secret);

			return $params;
		}

		protected function computeSignature ($parameters, $accessKeySecret) {
			// 将参数Key按字典顺序排序
			ksort($parameters);
			// 生成规范化请求字符串
			$canonicalizedQueryString = '';
			foreach ($parameters as $key => $value) {
				$canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
			}
			// 生成用于计算签名的字符串 stringToSign
			$stringToSign = 'GET&%2F&' . $this->percentEncode(substr($canonicalizedQueryString, 1));
			//echo "<br>".$stringToSign."<br>";
			// 计算签名，注意accessKeySecret后面要加上字符'&'
			$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));

			return $signature;
		}

		protected function percentEncode ($str) {
			// 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
			$res = urlencode($str);
			$res = preg_replace('/\+/', '%20', $res);
			$res = preg_replace('/\*/', '%2A', $res);
			$res = preg_replace('/%7E/', '~', $res);

			return $res;
		}

		//生成随机数
		function random ($length, $numeric = true) {
			$str = null;
			$mixture = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
			$number = '0123456789';
			$strBase = $numeric ? $number : $mixture;
			$max = strlen($strBase) - 1;

			for ($i = 0; $i < $length; $i++) {
				$str .= $strBase[rand(0, $max)];
			}

			return $str;
		}

		//xml格式转换成数组
		protected function XmlToArr ($xml) {
			libxml_disable_entity_loader(true);

			return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		}


	}


